#pragma once
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <unistd.h>
#include "Log.hpp"
using namespace log_ns;
const static std::string sep = ": "; //设置间隔符
//字典翻译类
class Dict{
    private:
        void LoadDict(const std::string& path) //文件加载到内存
        {
            std::ifstream in(path); //打开文件
            if(!in.is_open()) //判断是否打开
            {
                Log(FATAL, "open %s failed!\n", path);
                exit(1);
            }
            std::string line;
            while(std::getline(in, line)) //按行从文件中读取
            {
                Log(DEBUG, "load info: %s success\n", line.c_str());
                if(line.empty()) //行为空就继续
                    continue;
                auto pos = line.find(sep); //找到对应字串
                if(pos == std::string::npos) //判断是否找到
                    continue;
                std::string key = line.substr(0, pos); //截取从0到pos位置的字串，前闭后开
                if(key.empty())
                    continue;
                std::string value = line.substr(pos + sep.size()); //截取从pos + sep.size()位置一直到最后的字串
                if(value.empty())
                    continue;
                _dict.insert(std::make_pair(key, value)); //插入到哈希map中
            }
            Log(INFO, "load %s done\n", path.c_str());
            in.close();
        }
    public:
        Dict(const std::string& path)
        : _dict_path(path)
        {
            LoadDict(path);
        }
        std::string Translate(std::string word) //做英文翻译工作
        {
            if(word.empty())
                return "None";
            auto iter = _dict.find(word);
            return iter == _dict.end() ? "None" : iter->second; //找到返回对应的翻译，找不到返回None
                
        }
        ~Dict()
        {}
    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_path;
};
